<?php
class Application_Model_ReturnGoods extends Application_Model_DomainObject{
    
	protected $_id;
	
        protected $_datetime;      //创建时间

	protected $_storeItemId;   //仓库表id
	
	protected $_userId;       //用户表id
        
        protected $_productName;   //包裹名称
        
        protected $_returnReason;   //退换货原因
        
        protected $_logisticsName; //物流公司(仓库发件)

        protected $_logistics;      //物流单号(仓库发件)
        
        protected $_returnNote;    //退换货备注
        
        protected $_status;         //状态
        
        protected $_isDelete;     //标记删除：0代表不删除，1代表删除
        
        protected $_returnAddress;     //退货地址
        
        protected $_freight;     //运费(仓库发货)
        
        protected $_type;      //类型
        
        protected $_paytime;    //付款时间
        
        protected $_money;       //金额
        
        protected $_reDatetime;     //换货时间
        
        protected $_reLogisticsName;   //物流公司(仓库收件)
        
        protected $_reFreight;       //运费(仓库收件)

        protected $_reLogistics;      //物流单号(仓库收件)
        
        protected $_exception;        //异常信息
        
        protected $_source;         //来源
        
        protected $_dotime;            //操作时间
        
        protected $_problem;        //异常状态
        
        protected $_returnType;     //运费类型
        
        protected $_ckPass; // 判断是否通过 

        /**
         * 退货
         */
        const TYPE_Return = 1;
        
        /**
         * 换货
         */
        const TYPE_Change = 2;

        /**
         * 代购包裹
         */
       const SOURCE_Agency = 1;
       /**
        * 自助包裹
        */
       const SOURCE_Selfhelp = 2;
       /**
        * 上门取件
        */
       const SOURCE_Visiting = 3;       
       /**
        * 待付款
        */
       const STATUS_Forpayment = 0;
       /**
        * 已付款
        */
       const STATUS_Payment = 1;
       /**
        * 受理
        */
       const STATUS_Accepted = 2;
       /**
        * 处理中
        */
       const STATUS_Process = 3;
       /**
        * 已发包
        */
       const STATUS_Send = 4;
       /**
        * 已通知
        */
       const STATUS_Informed = 5;
       /**
        * 对方已收件
        */
       const STATUS_Received = 6;
      
       /**
        * 卖家已退款
        */
       const STATUS_Refund = 9;
       /**
        * 对方已发件
        */
       const STATUS_Resend = 10;
       /**
        * 仓库已收件
        */
       const STATUS_Receipt = 11;
       /**
        * 完成
        */
       const STATUS_Succeed = 12;
       /**
        * 代购商品退款给用户
        */
       const STATUS_Refee = 13;
       /**
        * 正常
        */
       const Problem_Defalut = 0;
       /**
        * 异常
        */
       const Problem_Exception = 1;
       /**
        * 已处理
        */
       const Problem_Process = 2;
       /**
        * 丢包
        */
       const Problem_Loss = 3;
       /**
        * 用户承担
        */
       const Return_User = 1;
       /**
        * 卖家承担
        */
       const Return_Seller = 2;
       /**
        * 悠奇承担
        */
       const Return_Uuch = 3;
       
       public function getStatusName(){
            switch ($this->_status) {
                case self::STATUS_Forpayment:
                    return "待付款";
                    break;
                case self::STATUS_Payment:
                    return "已付款";
                    break;
                case self::STATUS_Accepted:
                    return "已受理";
                    break;
                case self::STATUS_Process:
                    return "处理中";
                    break;
                case self::STATUS_Send:
                    return "已发包";
                    break;
                case self::STATUS_Informed:
                    return "已通知";
                    break;
                case self::STATUS_Received:
                    return "对方已收件";
                    break;
                case self::STATUS_Refund:
                    return "卖家已退款";
                    break;
                case self::STATUS_Resend:
                    return "对方已发件";
                    break;
                case self::STATUS_Receipt:
                    return "仓库已收件";
                    break;
                case self::STATUS_Succeed:
                    return "完成";
                    break;
                case self::STATUS_Refee:
                    return "已退款给用户";
                    break;;
                default:
                    return "未知状态";
                    break;
            }
      }
      public static function getProblemAll(){
          return array(
                    self::Problem_Defalut => "正常"
                  ,  self::Problem_Exception => "出现异常"
                  ,  self::Problem_Process => "异常处理"
                  ,  self::Problem_Loss => "包裹丢失"
          );
      }
      
      public function getProblemName()
      {
          $arrProblem = self::getProblemAll();
          return $arrProblem[$this->_problem];
      }

      public static function getStatusAll(){
        return array(
                   self::STATUS_Forpayment => "待付款"
                ,  self::STATUS_Payment=>"已付款"
                ,  self::STATUS_Accepted=>"已受理"
                ,  self::STATUS_Process=>"处理中"
                ,  self::STATUS_Send=>"已发包"
                ,  self::STATUS_Informed=>"已通知"
                ,  self::STATUS_Received=>"对方已收件"
                ,  self::STATUS_Refund=>"卖家已退款"
                ,  self::STATUS_Refee=>"已退款给用户"
                ,  self::STATUS_Resend=>"对方已发件"
                ,  self::STATUS_Receipt=>"仓库已收件"
                ,  self::STATUS_Succeed=>"完成"
        );
    }
      
      public function getTypeName(){
           switch ($this->_type) {
               case self::TYPE_Return:
                    return "退货";
                    break;
                case self::TYPE_Change:
                    return "换货";
                    break;
           }
      }
      
      public function getSourceName(){
          return "换货包裹";
      }
      
      /*代购退货流程*/
      public static function getStatusCorrect() {
            return array(
                self::STATUS_Accepted => array("待受理", "已受理")
                , self::STATUS_Process => array("待处理", "已处理")
                , self::STATUS_Send => array("待发包", "已发包")
                , self::STATUS_Informed => array("待通知","已通知")
                , self::STATUS_Received => array("对方待收件","对方已收件")
                , self::STATUS_Refund => array("卖家待退款","卖家已退款")
                , self::STATUS_Refee => array("待退款给用户","已退款给用户")
                , self::STATUS_Succeed => array("完成","完成")
            );
       }
       
       /*非代购退货流程*/
       public static function getStatusCorrect2() {
            return array(
                self::STATUS_Accepted => array("待受理", "已受理")
                , self::STATUS_Process => array("待处理", "已处理")
                , self::STATUS_Send => array("待发包", "已发包")
                , self::STATUS_Informed => array("待通知","已通知")
                , self::STATUS_Received => array("对方待收件","对方已收件")
                , self::STATUS_Succeed => array("完成","完成")
            );
       }
       
       /*换货流程*/
       public static function getStatusCorrect3() {
            return array(
                self::STATUS_Accepted => array("待受理", "已受理")
                , self::STATUS_Process => array("待处理", "已处理")
                , self::STATUS_Send => array("待发包", "已发包")
                , self::STATUS_Informed => array("待通知","已通知")
                , self::STATUS_Received => array("对方待收件","对方已收件")
                , self::STATUS_Resend => array("对方待发件","对方已发件")
                , self::STATUS_Receipt => array("仓库待收件","仓库已收件")
                , self::STATUS_Succeed => array("完成","完成")
            );
       }
       
       public static function getReturnTypeAll()
       {
           return array(
                    self::Return_User => "用户承担"
                   ,  self::Return_Seller => "卖家承担"
                   ,  self::Return_Uuch => "悠奇承担"
           );
       }
       
       public function getReturnTypeName()
       {
           $arrReturnType = $this->getReturnTypeAll();
           return $arrReturnType[$this->_returnType];
       }


       public function getUserInfo(){
             if($this->_userId){
                 return Application_Model_User::load($this->_userId);
             }
        }
        
        public function getStoreInfo(){
            if($this->_storeItemId){
                $id = "(" . $this->_storeItemId . "0)";
                $where[" id in "] = $id;
                return Application_Model_StoreItem::getDao()->queryAll($where);
            }
        }
        

        

        public static function getFilter($returnGoodsSearch,$pagesize,$pageindex){
//            var_dump($returnGoodsSearch->getSearchFileds());
              return self::getDao()->queryPage($returnGoodsSearch->getSearchFileds(), " id desc ", $pagesize, $pageindex);
        }
        
                
        public function addBillLog($interior, $description = null) {
            $billLogItem = Application_Model_WayLog::getByWayIdInteriorType($this->_id, $interior,  Application_Model_WayLog::Type_Return);
            if (!$billLogItem) {
                $billLogItem = new Application_Model_WayLog();
                $billLogItem->WayId = $this->_id;
                $billLogItem->OperateType = $interior;
            }        
            $billLogItem->DateCreated = date("Y-m-d H:i:s");
            $billLogItem->Operator = Uuch_Util::getUserNikeName();
            if ($description != null) {
                $billLogItem->Description = $description;
            } else {
                $billLogItem->Description = "退换货状态更改为：" . $this->getStatusName();
            }        
            $billLogItem->Type = Application_Model_WayLog::Type_Return;        
            $billLogItem->save();
        }
      
        /*根据状态获取的个数*/
        public static function getCountByStatus($status,$type = null,$problem = null){
            $where = array();
            $and = "";
            if($status !== null){
                $where[' status = '] = $status;
                $and = " and ";
            }
            if($type != null){
                $where[$and.' type = '] = $type;
                $and = " and ";
            }
            if($problem != null){
                $where[$and.' problem = '] = $problem;
                $and = " and ";
            }
            $where[$and.' ( isDelete is null or isDelete =0 ) and 1='] = 1;
            return self::getDao()->count($where);
        }
        /*获得超期的个数*/
        public static function getBeyondCount(){
            $where = array();
            $where[' dotime <= '] = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-4,date("Y")))." 23:59:59";
            $where[' and status != '] = Application_Model_ReturnGoods::STATUS_Succeed;
            $where[' and isDelete is null or isDelete = '] = 0;            
            return self::getDao()->count($where);
        }
        
       public function delLog() {
            $logItem = Application_Model_WayLog::getDao()->queryAll(array("wayId" => $this->_id, "and operateType<200 and operateType > " => $this->_status));
            if ($logItem) {
                foreach ($logItem as $logVal) {
                    $logVal->delete();
                }
            }
       }
      
       /**
        * 给用户发站内信
        */
       public function sendMessage($name, $userId, $type = null, $money = null){
            $messageItem = new Application_Model_Mail();
            $messageItem->Type = 2;
            $messageItem->Status = 0;
            $messageItem->UserId = $userId;
            $messageItem->DateCreated = date("Y-m-d H:i:s");
            if($type == 1){
                $messageItem->Title = $name . " 退货  扣运费 ￥".$money;
                $messageItem->Message = "尊敬的用户：您好！您的余额已不足扣运费，请及时充值!!";
            }else if($type == 2){
                $messageItem->Title = $name . " 换货  扣运费 ￥".$money;
                $messageItem->Message = "尊敬的用户：您好！您的余额已不足扣运费，请及时充值!!";
            }else{
                $messageItem->Title = $name . " 已退货";            
                $messageItem->Message = "尊敬的用户：您好！您的包裹（".$name.")卖家已收到";
            }
            $messageItem->save();
       }
       
       
       /**
        * 扣除用户的运费
        */
       public function deductFreight($barcode,$userId, $money, $reason){
           $userItem = Application_Model_UserAccount::load($userId);
           if($userItem){
               $beforeMoney = $userItem->Money;
               $userItem->Money = $userItem->Money - $money;
               $afterMoney = $userItem->Money;
               $userItem->save();
               $title = "系统自动扣款：￥" . $money;
               $content = "于" . date("Y-m-d H:i:s") . "系统自动扣款：" . $money . "(元)原因为：" . $reason;
               Application_Model_Operate::addOperate($money, null, $barcode, "退换货扣除客户运费：￥".$money, $userItem->id);
               $history = new Application_Model_UserAccountHistory();
               $history->Type = Application_Model_UserAccountHistory::TYPE_DISMONEY;
               $history->BeforeMoney = $beforeMoney;
               $history->AfterMoney = $afterMoney;
               $history->Comment = $reason;
               $history->DateCreated = date("Y-m-d H:i:s");
               $history->RelaseId = "1";
               $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
               $history->AccountId = $userId;
               $history->save();
               $messageItem = new Application_Model_Mail();
               $messageItem->Title = $title;
               $messageItem->UserId = $userId;
               $messageItem->Type = 2;
               $messageItem->Status = 0;
               $messageItem->Message = $content;
               $messageItem->DateCreated = date("Y-m-d H:i:s");
               $messageItem->save();
           }
       }
       
       public static function getByLogistics($logistics){
           return self::getDao()->queryOne(array("reLogistics"=>$logistics));
       }
}
